<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="审计计划：">
            <Input class="query-form-el" type="text" v-model="form1.auditPlanName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>

      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="openSelect">新增</Button>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据！" :loading="buttonLoading" size="small"
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>

    <Modal :title='add ? "审计计划新增":"审计计划修改"' :transfer=false v-model="model1" :width=800>
      <div style="height:500px;overflow-y:auto">
        <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="11">
              <FormItem label="审计计划：" prop="auditPlanName">
                <Input type="text" v-model="form1datacopy.auditPlanName" ></Input>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="审计年度：" prop="planStartTime">
                <DatePicker class="query-form-el" type="year" v-model="form1datacopy.planStartTime" format="yyyy"
                            placeholder="请选择"></DatePicker>
              </FormItem>
            </Col>
          </Row>
          <Row type="flex" justify="space-around" class="code-row-bg" style="margin-top: 20px">
            <Col span="23">
              <FormItem label="计划审计单位：" prop="companys">
                <div class='tag-input'>
                  <Tag  v-for='(tag, index) in form1datacopy.companys' :key='tag.orgId'
                        type="border" closable @on-close="removeNote(index)">{{tag.orgName}}</Tag>
                  <Button icon="ios-plus-empty" type="dashed" size="small" @click="addCompany">添加审计单位</Button>
                </div>
              </FormItem>
            </Col>
          </Row>

          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="11">
              <FormItem label="创建人：" prop="planStart">
                {{ form1datacopy.createUserName }}
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="创建时间：" prop="planEnd">
                {{ form1datacopy.createDate }}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
      <div slot="footer">
        <Button class='ivu-btn-save' :loading="loading" @click="submit('form1datacopy')">确定</Button>
        <Button class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>
    <Modal title="审计计划详情" v-model="model2" class="modal-view-detail" :width=800>
      <Form :model="showdata" :label-width="160">
        <Row type="flex" justify="space-around">
          <Col span="11">
            <FormItem label="审计计划：" prop="stdOrgName">
              {{ showdata.auditPlanName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="审计年度：">
              {{ formatDate(new Date(showdata.planStartTime), 'yyyy') }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg" style="margin-top: 20px">
          <Col span="23">
            <FormItem label="计划审计单位：" prop="companys">
              <div class='tag-input'>
                <!--                  <div v-for='(tag, index) in notes' :key='tag.orgId' class='tag-input__tag'>-->
                <!--                    {{ tag.orgNames }}-->
                <!--                  </div>-->
                <Tag  v-for='(tag, index) in showdata.companys' :key='tag.orgId'
                      type="border"  @on-close="removeNote(index)">{{tag.orgName}}</Tag>
              </div>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="创建人：" prop="planStart">
              {{ showdata.createUserName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="创建时间：" prop="planEnd">
              {{ showdata.createDate }}
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
      </div>
    </Modal>
    <Modal title="已审计单位" v-model="model10" class="modal-view-detail" :width=800>
      <Table ref='tables' :height="tableHeight" no-data-text="没有查询到相关数据！"  size="small"
             border :columns="columns2" :data="showdata.missionList">
      </Table>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model10=false">关闭</Button>
      </div>
    </Modal>
    <cascaderDom ref="cascaderDom" @setData="setNotes" >

    </cascaderDom>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import cascaderDom from '@/components/cascader-dom-multiple.vue'
import _deepclone from 'lodash/cloneDeep'

export default {
  components: {
    cascaderDom
  },
  data() {
    return {
      columns2: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index+1)
          }
        },
        {
          title: '所属二级集团',
          minWidth: 150,
          align: 'center',
          key: 'twoOrgName',
        },

        {
          title: '被审计单位',
          minWidth: 150,
          align: 'center',
          key: 'auditedOrgName',
        },
        {
          title: '审计状态',
          minWidth: 150,
          align: 'center',
          key: 'auditState',
        },
        {
          title: '审计时间',
          minWidth: 150,
          align: 'center',
          key: 'planDate',
        },
      ],
      model10:false,
      loading:false,
      fileUrl: Api.interestedPartiesUserFile,
      upLoadList1: [],
      appStatusList: [],
      locationList: [],
      stdRankList: [],
      downloadUrl: Api.downloadMongoFile,
      upUrl: Api.uploadMongoFile,
      form1: {},
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      dataTable: [],
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '审计计划名称',
          minWidth: 300,
          align: 'center',
          key: 'auditPlanName',
        },
        {
          title: '已审计单位',
          minWidth: 150,
          align: 'center',
          key: 'orgName',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.showdata = params.row;
                    this.model10 = true;
                  }
                }
              }, '点击查看')])
          }
        },
        {
          title: '审计年度',
          minWidth: 150,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.planStartTime), 'yyyy'))
            ]);
          }
        },
     /*   {
          title: '结束年度',
          minWidth: 150,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.planEndTime), 'yyyy'))
            ]);
          }
        },*/
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            let year = this.formatDate(new Date(params.row.planStartTime), 'yyyy');
            let nowYear = this.formatDate(new Date(), 'yyyy');
            //小于当前年份
            if (year < nowYear) {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                    color: '#d0d0d0',
                    pointerEvents: 'none'
                  },
                }, '新增审计单位'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {
                    fontSize: '14px',
                    color: '#d0d0d0',
                    pointerEvents: 'none'
                  },
                }, '删除')
              ]);
            } else {
              if (params.row.missionList.length > 0) {
                return h('div', [
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px'
                    },
                    on: {
                      click: () => {
                        this.showData(params, 1);
                      }
                    }
                  }, '详情'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px'
                    },
                    on: {
                      click: () => {
                        this.showData(params, 2);
                      }
                    }
                  }, '新增审计单位'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {
                      fontSize: '14px',
                      color: '#d0d0d0',
                      pointerEvents: 'none'
                    },
                  }, '删除')
                ]);
              } else {
                return h('div', [
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px'
                    },
                    on: {
                      click: () => {
                        this.showData(params, 1);
                      }
                    }
                  }, '详情'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px'
                    },
                    on: {
                      click: () => {
                        this.showData(params, 2);
                      }
                    }
                  }, '新增审计单位'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px',
                      color: 'red'
                    },
                    on: {
                      click: () => {
                        this.deleteData(params);
                      }
                    }
                  }, '删除')
                ]);

              }
            }


          }
        },

      ],
      ruleCustom: {
        auditPlanName: [{
          required: true,
          message: '  ',
          trigger: 'change'
        }],
        planStartTime: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        companys: [{
          validator: (rule, value, callback) => {
            if (!value) {
              callback(" ")
              this.$Message.error("请添加审计单位！");
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        planEndTime: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],

      },
      auditedOrgName: '',
      auditedOrgId: '',
      add: false,
      model1: false,
      model2: false,
      showdata: {},
      location: null,
      form1datacopy: {
        appraiseScore: 0,
        appraiseRank: ''
      },
      files: [],
      buttonLoading: false, tableHeight: 10,
    }
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    //this.selectCodingSort();
    this.query();
  },
  methods: {
    addCompany(){
      this.$refs.cascaderDom.openOrgModal(_deepclone(this.form1datacopy.companys));
    },
    setNotes(data){
      this.$set(this.form1datacopy,'companys',data)
      this.$forceUpdate();
    },
    removeNote(index){
      this.form1datacopy.companys.splice(index, 1)
      this.$forceUpdate();
    },
    downloadFile(guideId, file) {
      let url = this.fileUrl + '/file/' + file.id;
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        console.log(res)
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    changeSelect(val) {
      console.log('this.form1datacopy.appraiseRank=', val)
      this.form1datacopy.appraiseRank = val.id
    },
    onCancel() {
      this.model2 = false
    },
    closeModal1() {
      this.expertSelectModal = false;
    },
    deleteFile(index) {
      this.files.splice(index, 1);
    },
    deleteData(params) {
      this.$Modal.confirm({
        title: '数据删除',
        content: '<p>确定删除该条信息</p>',
        okText: '确认',
        onOk: () => {
          let url = Api.deleteAdtplan;
          this.$http.get(url, {params: {id: params.row.auditPlanId}}).then((res) => {
            if (res.status === 200) {
              this.$Message.success('成功');
              this.query()
            } else if (res.data.status === 201) {
              this.$Message.error(res.data.msg);

            }
          }).catch(e => {
            this.$Message.error('请求失败' + e);
          })
        },
        cancelText: '取消'
      });
    },

    openSelect() {
      this.form1datacopy = {}
      this.form1datacopy.planStartTime = new Date()
      var d = new Date()
      d.setFullYear(d.getFullYear() + 2)
      this.form1datacopy.planEndTime = d

      let userName = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserName"]
      this.form1datacopy.createDate = this.formatDate(new Date(), 'yyyy-MM-dd'),
          this.form1datacopy.createUserName = userName,
          this.model1 = true;
      this.add = true;
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    selectCodingSort() {
      this.$http.get(Api.queryCodeDetailBySortId + '/AS-000001', {params: {}}).then((res) => {
        this.appStatusList = res.data.data;
      });
      this.$http.get(Api.queryCodeDetailBySortId + '/REGION-000001', {params: {}}).then((res) => {
        this.locationList = res.data.data;
      });
      this.$http.get(Api.queryCodeDetailBySortId + '/SSL-000001', {params: {}}).then((res) => {
        this.stdRankList = res.data.data;
      });

    },
    reset() {
      this.form1 = {};
      this.query();


    },
    query() {
      this.buttonLoading = true
      let userId = sessionStorage('userId').getObject('userId').userId;
      let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        orgId: orgId
      };
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      data.auditPlanName = this.form1.auditPlanName || ''
      let url = Api.queryAdtPlan;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data;
        this.pagedata.total = res.data.totalSize;
        this.buttonLoading = false
      }).catch(e => {
        console.error(e)
        this.$Message.error("数据获取失败")
      })
    },
    showData(data, flag) {
      this.auditedOrgId = data.row.auditedOrgId;
      this.auditedOrgName = data.row.auditedOrgName;
      data.row.createDate = this.formatDate(new Date(data.row.createDate), 'yyyy-MM-dd')
      if (flag == 1) {
        //查看页面
        // this.$http.get(Api.interestedPartiesUserFile+"/"+data.row.standardId +"/files/file", ).then((res) => {
        //     this.files = res.data.data;
        //     console.log(this.files)


        // }).catch(e => {
        //     this.$Message.error("数据获取失败")
        // });
        this.showdata = JSON.parse(JSON.stringify(data.row));
        if (data.row.notes){
          this.showdata.companys = JSON.parse(data.row.notes);
        }
        this.model2 = true;
      } else {
        this.add = false;
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        this.form1datacopy.companys = JSON.parse(data.row.notes);
        this.model1 = true;
      }
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },

    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          //this.form1datacopy.planStart = this.formatDate(new Date(this.form1datacopy.planStart), 'yyyy-MM-dd');
          //this.form1datacopy.planEnd = this.formatDate(new Date(this.form1datacopy.planEnd), 'yyyy-MM-dd');
          this.loading = true;
          this.form1datacopy.notes = JSON.stringify(this.form1datacopy.companys)
          if (this.add) {
            let userId = sessionStorage('userId').getObject('userId').userId;
            let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
            this.form1datacopy.createUserId = userId;
            this.form1datacopy.createOrgId = orgId;

            this.$http.post(Api.createAdtPlan, this.form1datacopy).then((res) => {
              this.loading =false;
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.query()

              } else if (res.data.status === 201) {
                this.$Message.error(res.data.msg);

              }

            }).catch(e => {
              this.loading =false;
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          } else {
            let userId = sessionStorage('userId').getObject('userId').userId;
            let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
            this.form1datacopy.updateUserId = userId;
            this.form1datacopy.updateOrgId = orgId;
            this.$http.post(Api.createAdtPlan, this.form1datacopy).then((res) => {
              this.loading =false;
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.query()

              } else if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
                // this.model1 = false;
              }

            }).catch(e => {
              this.loading =false;
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          }


        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      console.log(a);
      return a;
    },
  },
  watch: {

    "uploadList1": function (val1, val2) {
      //console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
      //console.log('val1',val1)
      //console.log('val2',val2)

    },
    "model1": function (qw, er) {
      if (qw && this.model1) {
        setTimeout(() => {
          //this.$refs.trainOrg.setCurrentOrg();

        }, 100)
      } else {
        //this.$refs.trainOrg.setCurrentOrg();

      }
    }

  }
}
</script>

<style lang='css' scoped>
@import '../../../index.css';
.tag-input {
  width: 100%;
  border: 1px solid #eee;
  font-size: 0.9em;
  height: 100px;
  box-sizing: border-box;
  padding: 0 10px;
  overflow-y: auto;
}

.tag-input__tag {
  height: 30px;
  float: left;
  margin-right: 10px;
  background-color: #eee;
  margin-top: 10px;
  line-height: 30px;
  padding: 0 5px;
  border-radius: 5px;
}

.tag-input__tag > span {
  cursor: pointer;
  opacity: 0.75;
}

.tag-input__text {
  border: none;
  outline: none;
  font-size: 0.9em;
  line-height: 50px;
  background: none;
}
</style>
